#define _CRT_SECURE_NO_WARNINGS 1

#include<iostream>
#include<vector>
#include<queue>
using namespace std;


struct TreeNode {
	int val;
	TreeNode* left;
	TreeNode* right;
	TreeNode() : val(0), left(nullptr), right(nullptr) {}
	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
	TreeNode(int x, TreeNode* left, TreeNode* right) : val(x), left(left), right(right) {}
};

class Solution {
public:
    size_t height(TreeNode* root)
    {
        if (root == nullptr)
            return 0;
        size_t left = height(root->left);
        size_t right = height(root->right);
        return 1 + (left < right ? right : left);
    }
    vector<vector<int>> levelOrder(TreeNode* root) {
        if (root == nullptr) return vector<vector<int>>();
        queue<TreeNode*> st;
        st.push(root);
        vector<vector<int>> vv;
        vv.resize(height(root));
        int high = 0;

        while (!st.empty())
        {
            int width = st.size();
            vv[high].resize(width);
            int i = 0;
            while (width--)
            {
                TreeNode* tmp = st.front();
                st.pop();
                vv[high][i++] = tmp->val;
                if (tmp->left)
                    st.push(tmp->left);
                if (tmp->right)
                    st.push(tmp->right);
            }
            high++;
        }

        return vv;
    }
};

int main()
{
    TreeNode t1(3);
    TreeNode t2(9);
    TreeNode t3(20);
    TreeNode t4(15);
    TreeNode t5(7);
    t1.left = &t2;
    t1.right = &t3;
    t3.left = &t4;
    t3.right = &t5;
    Solution s;

    vector<vector<int>> vv = s.levelOrder(&t1);
    for (int i = 0; i < vv.size(); i++)
    {
        for (int j = 0; j < vv[i].size(); j++)
            cout << vv[i][j] << ' ';
        cout << endl;
    }
    return 0;
}